package com.zr.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.zr.model.User;
import com.zr.service.UserService;
import com.zr.service.impl.UserServiceImpl;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    UserService userService = new UserServiceImpl();

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("utf8");
        PrintWriter writer = response.getWriter();
        String userName = request.getParameter("userName");
        String userPassWd = request.getParameter("userPassWd");
        User user = userService.login(userName, userPassWd);
        JSONObject jsonObject = new JSONObject();
        if (user.getUserId() != 0) {
            request.getSession().setAttribute("user", user);
            jsonObject.put("success", true);
            writer.write(jsonObject.toString());
        } else {
            jsonObject.put("success", false);
            writer.write(jsonObject.toString());
        }

    }

}
